package com.cindata

import com.cindata.dictionary.*
import com.cindata.dimension.YearLimitDimension

import static org.springframework.http.HttpStatus.*
import grails.gorm.transactions.Transactional

import org.springframework.security.access.annotation.Secured

@Secured(['isAuthenticated()'])
@Transactional
class AbnormalMortgageBatchController {

    static allowedMethods = [save: "POST", update: "PUT", delete: "DELETE"]

    def abnormalMortgageBatchService
    def springSecurityService

    def index() {
        def max = Math.min(params.max ? params.max.toInteger() : 10, 100)
        def offset = params.offset ? params.offset.toInteger() : 0
        def name = params["name"]
        def disposeMethod = params["disposeMethod"]

        def user = User.findById(springSecurityService.principal.id)
        //查询待处理的资产包
        def sql = " from AbnormalMortgageBatch a where a.account.id in " + Account.FilterAccountSql(user)
        def queryParam = [:]
        if (name && name != "")
        {
          sql += " and a.name like :name "
          queryParam['name'] = "%" + name + "%"
        }
        if (disposeMethod && disposeMethod != "")
        {
          sql += " and a.disposeMethod =  :disposeMethod "
          queryParam['disposeMethod'] = disposeMethod
        }
        sql += " order by a.modifiedDate desc"
        def abnormalMortgageBatchList = AbnormalMortgageBatch.executeQuery(sql, queryParam, [max: max, offset: offset])
        def abnormalMortgageBatchCount = AbnormalMortgageBatch.executeQuery(sql, queryParam)
        respond abnormalMortgageBatchList, model:[abnormalMortgageBatchCount: abnormalMortgageBatchCount?.size(), params: params]
    }

    def show(AbnormalMortgageBatch abnormalMortgageBatch) {
        def max = Math.min(params.max ? params.max.toInteger() : 10, 100)
        def offset = params.offset ? params.offset.toInteger() : 0
        def city = params["city"]
        def loansDuration = params["loansDuration"]
        def mortgageStatus = params["mortgageStatus"]
        def loansAmountStart = params["loansAmountStart"]
        def loansAmountEnd = params["loansAmountEnd"]
        def loansBalanceStart = params["loansBalanceStart"]
        def loansBalanceEnd = params["loansBalanceEnd"]
        def isNonPerformingLoan = params["isNonPerformingLoan"]
        def startDateStart = params["startDateStart"]
        def startDateEnd = params["startDateEnd"]
        def accountId = params["accountId"]
        def mortgageType = params["mortgageType"]
        def mortgagePattern = params["mortgagePattern"]
        def mortgageCategory = params["mortgageCategory"]
        def riskWarningLevel = params["riskWarningLevel"]
        def serialNumber = params["serialNumber"]

        def user = User.findById(springSecurityService.principal.id)
        def mortgageQueryParam = new HashMap()
        def mortgageSql = " from BatchMortgage bm where bm.abnormalMortgageBatch.id = ${abnormalMortgageBatch?.id} and bm.mortgage.account.id in " + Account.FilterAccountSql(user)

        def sql = " "
        if (city && city != "-1")
        {
            sql += " and bm.mortgage.account.city.zoneNumber = :city "
            mortgageQueryParam["city"] = city
        }
        if (loansDuration && loansDuration != "")
        {
            def yearList = YearLimitDimension.list()
            yearList.each {
                if (it?.label == loansDuration)
                {
                    def loansDurationMin = it.minValue
                    def loansDurationMax = it.maxValue
                    sql += " and bm.mortgage.loansDuration > :loansDurationMin and bm.mortgage.loansDuration<= :loansDurationMax "
                    mortgageQueryParam['loansDurationMin'] = loansDurationMin
                    mortgageQueryParam['loansDurationMax'] = loansDurationMax
                }
            }
        }
        if (mortgageStatus && mortgageStatus != "")
        {
            sql += " and bm.mortgage.mortgageStatus.id = :mortgageStatus "
            mortgageQueryParam['mortgageStatus'] = Long.parseLong(mortgageStatus)
        }
        if (loansAmountStart && loansAmountStart != '')
        {
            sql += "and bm.mortgage.loansAmount >= :loansAmountStart "
            mortgageQueryParam['loansAmountStart'] = new BigDecimal(loansAmountStart) * 10000
        }
        if (loansAmountEnd && loansAmountEnd != '')
        {
            sql += "and bm.mortgage.loansAmount <= :loansAmountEnd "
            mortgageQueryParam['loansAmountEnd'] = new BigDecimal(loansAmountEnd) * 10000
        }
        if (loansBalanceStart && loansBalanceStart != '')
        {
            sql += "and bm.mortgage.loansBalance >= :loansBalanceStart "
            mortgageQueryParam['loansBalanceStart'] = new BigDecimal(loansBalanceStart) * 10000
        }
        if (loansBalanceEnd && loansBalanceEnd != '')
        {
            sql += "and bm.mortgage.loansBalance <= :loansBalanceEnd "
            mortgageQueryParam['loansBalanceEnd'] = new BigDecimal(loansBalanceEnd) * 10000
        }
        if (isNonPerformingLoan && isNonPerformingLoan != "")
        {
            sql += " and bm.mortgage.isNonPerformingLoan = :isNonPerformingLoan "
            mortgageQueryParam['isNonPerformingLoan'] = Boolean.parseBoolean(isNonPerformingLoan)
        }
        if (startDateStart)
        {
            //中文日期转换
            def dateStart = DateUtil.GetDateBeginByDateStr(startDateStart)
            sql += "and bm.mortgage.startDate >=  :dateStart "
            mortgageQueryParam['dateStart'] = dateStart
        }
        if (startDateEnd)
        {
            //中文日期转换
            def dateEnd = DateUtil.GetNextDateBeginByDateStr(startDateEnd)
            sql += "and bm.mortgage.startDate <=  :dateEnd "
            mortgageQueryParam['dateEnd'] = dateEnd
        }
        if (accountId && accountId != "")
        {
            sql += " and bm.mortgage.account.id = :accountId "
            mortgageQueryParam['accountId'] = Long.parseLong(accountId)
        }
        if (mortgagePattern && mortgagePattern != "")
        {
            sql += " and bm.mortgage.mortgagePattern.id = :mortgagePattern "
            mortgageQueryParam['mortgagePattern'] = Long.parseLong(mortgagePattern)
        }
        if (mortgageType && mortgageType != "")
        {
            sql += " and bm.mortgage.mortgageType.id = :mortgageType "
            mortgageQueryParam['mortgageType'] = Long.parseLong(mortgageType)
        }
        if (mortgageCategory && mortgageCategory != "")
        {
            sql += " and bm.mortgage.mortgageCategory.id = :mortgageCategory "
            mortgageQueryParam['mortgageCategory'] = Long.parseLong(mortgageCategory)
        }
        if (riskWarningLevel && riskWarningLevel != "")
        {
            sql += " and bm.mortgage.riskWarningLevel.id = :riskWarningLevel "
            mortgageQueryParam['riskWarningLevel'] = Long.parseLong(riskWarningLevel)
        }
        if (serialNumber && serialNumber != "")
        {
            sql += " and bm.mortgage.serialNumber = :serialNumber "
            mortgageQueryParam['serialNumber'] = serialNumber
        }

        def countSql = " select count(bm.id) "
        mortgageSql += sql
        countSql += mortgageSql
        mortgageSql += "order by bm.mortgage.serialNumber desc "

        def batchMortgageList = BatchMortgage.executeQuery(mortgageSql, mortgageQueryParam, [max: max, offset: offset])
        def batchMortgageCount = BatchMortgage.executeQuery(countSql, mortgageQueryParam)

        def accountManageAccountSql = " from Account o where o.id in  " + Account.FilterAccountSql(user)
        def accountManageAccountList = Account.executeQuery(accountManageAccountSql)

        respond abnormalMortgageBatch, model:[batchMortgageList: batchMortgageList, batchMortgageCount: batchMortgageCount[0], accountManageAccountList: accountManageAccountList, params: params]
    }

    def pendingIndex() {
        def max = Math.min(params.max ? params.max.toInteger() : 10, 100)
        def offset = params.offset ? params.offset.toInteger() : 0
        def name = params["name"]
        def disposeMethod = params["disposeMethod"]

        def user = User.findById(springSecurityService.principal.id)

        //查询待处理的资产包
        def sql = " from WorkflowInstance f where f.abnormalMortgageBatch is not null and f.status.name = 'Pending' and f.stage.id in (select stage.id from WorkflowInstanceUser where authority.name = 'Approval' and user.id = ${user?.id})  and f.abnormalMortgageBatch.account.id in " + Account.FilterAccountSql(user)
        def queryParam = [:]
        if (name && name != "")
        {
            sql += " and f.abnormalMortgageBatch.name like :name "
            queryParam['name'] = "%" + name + "%"
        }
        if (disposeMethod && disposeMethod != "")
        {
            sql += " and f.abnormalMortgageBatch.disposeMethod =  :disposeMethod "
            queryParam['disposeMethod'] = disposeMethod
        }
        sql += " order by f.modifiedDate desc"
        def workflowInstanceList = AbnormalMortgageBatch.executeQuery(sql, queryParam, [max: max, offset: offset])
        def workflowInstanceCount = AbnormalMortgageBatch.executeQuery(sql, queryParam)
        respond workflowInstanceList, model:[workflowInstanceCount: workflowInstanceCount?.size(), params: params]
    }

    def pendingShow(WorkflowInstance workflowInstance) {
        def abnormalMortgageBatch = workflowInstance?.abnormalMortgageBatch
        def max = Math.min(params.max ? params.max.toInteger() : 10, 100)
        def offset = params.offset ? params.offset.toInteger() : 0
        def city = params["city"]
        def loansDuration = params["loansDuration"]
        def mortgageStatus = params["mortgageStatus"]
        def loansAmountStart = params["loansAmountStart"]
        def loansAmountEnd = params["loansAmountEnd"]
        def loansBalanceStart = params["loansBalanceStart"]
        def loansBalanceEnd = params["loansBalanceEnd"]
        def isNonPerformingLoan = params["isNonPerformingLoan"]
        def startDateStart = params["startDateStart"]
        def startDateEnd = params["startDateEnd"]
        def accountId = params["accountId"]
        def mortgageType = params["mortgageType"]
        def mortgagePattern = params["mortgagePattern"]
        def mortgageCategory = params["mortgageCategory"]
        def riskWarningLevel = params["riskWarningLevel"]
        def serialNumber = params["serialNumber"]

        def user = User.findById(springSecurityService.principal.id)
        def mortgageQueryParam = new HashMap()
        def mortgageSql = " from BatchMortgage bm where bm.abnormalMortgageBatch.id = ${abnormalMortgageBatch?.id} and bm.mortgage.account.id in " + Account.FilterAccountSql(user)

        def sql = " "
        if (city && city != "-1")
        {
            sql += " and bm.mortgage.account.city.zoneNumber = :city "
            mortgageQueryParam["city"] = city
        }
        if (loansDuration && loansDuration != "")
        {
            def yearList = YearLimitDimension.list()
            yearList.each {
                if (it?.label == loansDuration)
                {
                    def loansDurationMin = it.minValue
                    def loansDurationMax = it.maxValue
                    sql += " and bm.mortgage.loansDuration > :loansDurationMin and bm.mortgage.loansDuration<= :loansDurationMax "
                    mortgageQueryParam['loansDurationMin'] = loansDurationMin
                    mortgageQueryParam['loansDurationMax'] = loansDurationMax
                }
            }
        }
        if (mortgageStatus && mortgageStatus != "")
        {
            sql += " and bm.mortgage.mortgageStatus.id = :mortgageStatus "
            mortgageQueryParam['mortgageStatus'] = Long.parseLong(mortgageStatus)
        }
        if (loansAmountStart && loansAmountStart != '')
        {
            sql += "and bm.mortgage.loansAmount >= :loansAmountStart "
            mortgageQueryParam['loansAmountStart'] = new BigDecimal(loansAmountStart) * 10000
        }
        if (loansAmountEnd && loansAmountEnd != '')
        {
            sql += "and bm.mortgage.loansAmount <= :loansAmountEnd "
            mortgageQueryParam['loansAmountEnd'] = new BigDecimal(loansAmountEnd) * 10000
        }
        if (loansBalanceStart && loansBalanceStart != '')
        {
            sql += "and bm.mortgage.loansBalance >= :loansBalanceStart "
            mortgageQueryParam['loansBalanceStart'] = new BigDecimal(loansBalanceStart) * 10000
        }
        if (loansBalanceEnd && loansBalanceEnd != '')
        {
            sql += "and bm.mortgage.loansBalance <= :loansBalanceEnd "
            mortgageQueryParam['loansBalanceEnd'] = new BigDecimal(loansBalanceEnd) * 10000
        }
        if (isNonPerformingLoan && isNonPerformingLoan != "")
        {
            sql += " and bm.mortgage.isNonPerformingLoan = :isNonPerformingLoan "
            mortgageQueryParam['isNonPerformingLoan'] = Boolean.parseBoolean(isNonPerformingLoan)
        }
        if (startDateStart)
        {
            //中文日期转换
            def dateStart = DateUtil.GetDateBeginByDateStr(startDateStart)
            sql += "and bm.mortgage.startDate >=  :dateStart "
            mortgageQueryParam['dateStart'] = dateStart
        }
        if (startDateEnd)
        {
            //中文日期转换
            def dateEnd = DateUtil.GetNextDateBeginByDateStr(startDateEnd)
            sql += "and bm.mortgage.startDate <=  :dateEnd "
            mortgageQueryParam['dateEnd'] = dateEnd
        }
        if (accountId && accountId != "")
        {
            sql += " and bm.mortgage.account.id = :accountId "
            mortgageQueryParam['accountId'] = Long.parseLong(accountId)
        }
        if (mortgagePattern && mortgagePattern != "")
        {
            sql += " and bm.mortgage.mortgagePattern.id = :mortgagePattern "
            mortgageQueryParam['mortgagePattern'] = Long.parseLong(mortgagePattern)
        }
        if (mortgageType && mortgageType != "")
        {
            sql += " and bm.mortgage.mortgageType.id = :mortgageType "
            mortgageQueryParam['mortgageType'] = Long.parseLong(mortgageType)
        }
        if (mortgageCategory && mortgageCategory != "")
        {
            sql += " and bm.mortgage.mortgageCategory.id = :mortgageCategory "
            mortgageQueryParam['mortgageCategory'] = Long.parseLong(mortgageCategory)
        }
        if (riskWarningLevel && riskWarningLevel != "")
        {
            sql += " and bm.mortgage.riskWarningLevel.id = :riskWarningLevel "
            mortgageQueryParam['riskWarningLevel'] = Long.parseLong(riskWarningLevel)
        }
        if (serialNumber && serialNumber != "")
        {
            sql += " and bm.mortgage.serialNumber = :serialNumber "
            mortgageQueryParam['serialNumber'] = serialNumber
        }

        def countSql = " select count(bm.id) "
        mortgageSql += sql
        countSql += mortgageSql
        mortgageSql += "order by bm.mortgage.serialNumber desc "

        def batchMortgageList = BatchMortgage.executeQuery(mortgageSql, mortgageQueryParam, [max: max, offset: offset])
        def batchMortgageCount = BatchMortgage.executeQuery(countSql, mortgageQueryParam)

        def accountManageAccountSql = " from Account o where o.id in  " + Account.FilterAccountSql(user)
        def accountManageAccountList = Account.executeQuery(accountManageAccountSql)
        //
        def flowStage = workflowInstance?.stage
        def editRoleFlag = false
        def approveRoleFlag = false
        if (flowStage)
        {
            editRoleFlag = WorkflowInstanceUser.find("from WorkflowInstanceUser where stage.id = ? and authority.id = ? and user.id = ? ", [flowStage?.id, WorkflowAuthority.EDIT()?.id,user?.id]) && true
            approveRoleFlag = WorkflowInstanceUser.find("from WorkflowInstanceUser where stage.id = ? and authority.id = ? and user.id = ? " , [flowStage?.id, WorkflowAuthority.APPROVAL()?.id,user?.id]) && true
        }
        //
        def layout = flowStage?.layout?.name

        respond abnormalMortgageBatch, model:[workflowInstance: workflowInstance, batchMortgageList: batchMortgageList, batchMortgageCount: batchMortgageCount[0], accountManageAccountList: accountManageAccountList, params: params, editRoleFlag: editRoleFlag, approveRoleFlag: approveRoleFlag], view: layout
    }

    def create() {
        respond new AbnormalMortgageBatch(params)
    }

    @Transactional
    def save(AbnormalMortgageBatch abnormalMortgageBatch) {
        if (abnormalMortgageBatch == null) {transactionStatus.setRollbackOnly()
            notFound()
            return
        }

        if (abnormalMortgageBatch.hasErrors()) {
            transactionStatus.setRollbackOnly()
            respond abnormalMortgageBatch.errors, view:'create'
            return
        }

        abnormalMortgageBatch.save flush:true

        redirect(url: params.targetUri)
    }

    def edit(AbnormalMortgageBatch abnormalMortgageBatch) {
        params.targetUri = request.getHeader("referer")
        respond abnormalMortgageBatch
    }

    @Transactional
    def update(AbnormalMortgageBatch abnormalMortgageBatch) {
        if (abnormalMortgageBatch == null) {
            transactionStatus.setRollbackOnly()
            notFound()
            return
        }

        if (abnormalMortgageBatch.hasErrors()) {
            transactionStatus.setRollbackOnly()
            respond abnormalMortgageBatch.errors, view:'edit'
            return
        }

        abnormalMortgageBatch.save flush:true

        redirect(url: params.targetUri)
    }

    def edit1(AbnormalMortgageBatch abnormalMortgageBatch) {
        params.targetUri = request.getHeader("referer")
        respond abnormalMortgageBatch
    }

    @Transactional
    def update1(AbnormalMortgageBatch abnormalMortgageBatch) {
        if (abnormalMortgageBatch == null) {
            transactionStatus.setRollbackOnly()
            notFound()
            return
        }

        if (abnormalMortgageBatch.hasErrors()) {
            transactionStatus.setRollbackOnly()
            respond abnormalMortgageBatch.errors, view:'edit1'
            return
        }

        abnormalMortgageBatch.save flush:true

       redirect(url: params.targetUri)
    }

    @Transactional
    def delete(AbnormalMortgageBatch abnormalMortgageBatch) {

        if (abnormalMortgageBatch == null) {
            transactionStatus.setRollbackOnly()
            notFound()
            return
        }

        abnormalMortgageBatch.delete flush:true

        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.deleted.message', args: [message(code: 'abnormalMortgageBatch.label', default: 'AbnormalMortgageBatch'), abnormalMortgageBatch.id])
                redirect action:"index", method:"GET"
            }
            '*'{ render status: NO_CONTENT }
        }
    }

    protected void notFound() {
        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.not.found.message', args: [message(code: 'abnormalMortgageBatch.label', default: 'AbnormalMortgageBatch'), params.id])
                redirect action: "index", method: "GET"
            }
            '*'{ render status: NOT_FOUND }
        }
    }

    @Transactional
    def batchSave(AbnormalMortgageBatch abnormalMortgageBatch) 
    {
        if (AbnormalMortgageBatch.findByName(abnormalMortgageBatch?.name))
        {
            flash.message = "资产包名称已存在！"
            redirect controller:'mortgage', action: 'index'
            return
        }
        abnormalMortgageBatch.save()

        def max = Math.min(params.max ? params.max.toInteger() : 10, 100)
        def offset = params.offset ? params.offset.toInteger() : 0
        def city = params["city"]
        def loansDuration = params["loansDuration"]
        def mortgageStatus = params["mortgageStatus"]
        def loansAmountStart = params["loansAmountStart"]
        def loansAmountEnd = params["loansAmountEnd"]
        def loansBalanceStart = params["loansBalanceStart"]
        def loansBalanceEnd = params["loansBalanceEnd"]
        def isNonPerformingLoan = params["isNonPerformingLoan"]
        def startDateStart = params["startDateStart"]
        def startDateEnd = params["startDateEnd"]
        def accountId = params["accountId"]
        def mortgageType = params["mortgageType"]
        def mortgagePattern = params["mortgagePattern"]
        def mortgageCategory = params["mortgageCategory"]
        def riskWarningLevel = params["riskWarningLevel"]
        def serialNumber = params["serialNumber"]

        def user = User.findById(springSecurityService.principal.id)
        def mortgageQueryParam = new HashMap()
        def mortgageSql = " from Mortgage e where e.account.id in " + Account.FilterAccountSql(user)

        def sql = " "
        if (city && city != "-1")
        {
            sql += " and e.account.city.zoneNumber = :city "
            mortgageQueryParam["city"] = city
        }
        if (loansDuration && loansDuration != "")
        {
            def yearList = YearLimitDimension.list()
            yearList.each {
                if (it?.label == loansDuration)
                {
                    def loansDurationMin = it.minValue
                    def loansDurationMax = it.maxValue
                    sql += " and e.loansDuration > :loansDurationMin and e.loansDuration<= :loansDurationMax "
                    mortgageQueryParam['loansDurationMin'] = loansDurationMin
                    mortgageQueryParam['loansDurationMax'] = loansDurationMax
                }
            }
        }
        if (mortgageStatus && mortgageStatus != "")
        {
            sql += " and e.mortgageStatus.id = :mortgageStatus "
            mortgageQueryParam['mortgageStatus'] = Long.parseLong(mortgageStatus)
        }
        if (loansAmountStart && loansAmountStart != '')
        {
            sql += "and e.loansAmount >= :loansAmountStart "
            mortgageQueryParam['loansAmountStart'] = new BigDecimal(loansAmountStart) * 10000
        }
        if (loansAmountEnd && loansAmountEnd != '')
        {
            sql += "and e.loansAmount <= :loansAmountEnd "
            mortgageQueryParam['loansAmountEnd'] = new BigDecimal(loansAmountEnd) * 10000
        }
        if (loansBalanceStart && loansBalanceStart != '')
        {
            sql += "and e.loansBalance >= :loansBalanceStart "
            mortgageQueryParam['loansBalanceStart'] = new BigDecimal(loansBalanceStart) * 10000
        }
        if (loansBalanceEnd && loansBalanceEnd != '')
        {
            sql += "and e.loansBalance <= :loansBalanceEnd "
            mortgageQueryParam['loansBalanceEnd'] = new BigDecimal(loansBalanceEnd) * 10000
        }
        if (isNonPerformingLoan && isNonPerformingLoan != "")
        {
            sql += " and e.isNonPerformingLoan = :isNonPerformingLoan "
            mortgageQueryParam['isNonPerformingLoan'] = Boolean.parseBoolean(isNonPerformingLoan)
        }
        if (startDateStart)
        {
            //中文日期转换
            def dateStart = DateUtil.GetDateBeginByDateStr(startDateStart)
            sql += "and e.startDate >=  :dateStart "
            mortgageQueryParam['dateStart'] = dateStart
        }
        if (startDateEnd)
        {
            //中文日期转换
            def dateEnd = DateUtil.GetNextDateBeginByDateStr(startDateEnd)
            sql += "and e.startDate <=  :dateEnd "
            mortgageQueryParam['dateEnd'] = dateEnd
        }
        if (accountId && accountId != "")
        {
            sql += " and e.account.id = :accountId "
            mortgageQueryParam['accountId'] = Long.parseLong(accountId)
        }
        if (mortgagePattern && mortgagePattern != "")
        {
            sql += " and e.mortgagePattern.id = :mortgagePattern "
            mortgageQueryParam['mortgagePattern'] = Long.parseLong(mortgagePattern)
        }
        if (mortgageType && mortgageType != "")
        {
            sql += " and e.mortgageType.id = :mortgageType "
            mortgageQueryParam['mortgageType'] = Long.parseLong(mortgageType)
        }
        if (mortgageCategory && mortgageCategory != "")
        {
            sql += " and e.mortgageCategory.id = :mortgageCategory "
            mortgageQueryParam['mortgageCategory'] = Long.parseLong(mortgageCategory)
        }
        if (riskWarningLevel && riskWarningLevel != "")
        {
            sql += " and e.riskWarningLevel.id = :riskWarningLevel "
            mortgageQueryParam['riskWarningLevel'] = Long.parseLong(riskWarningLevel)
        }
        if (serialNumber) 
        {
            sql += " and e.serialNumber like :serialNumber "
            mortgageQueryParam['serialNumber'] = "%" + serialNumber + "%"
        }

        def countSql = " select count(e.id) from Mortgage e where e.account.id in " + Account.FilterAccountSql(user)

        countSql += sql
        sql += "order by e.serialNumber desc "
        mortgageSql += sql

        def mortgageList = Mortgage.executeQuery(mortgageSql, mortgageQueryParam)

        mortgageList?.each {
          def batchMortgage = new BatchMortgage(mortgage: it)
          abnormalMortgageBatch.addToMortgages(batchMortgage)
        }

        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.created.message', args: [message(code: 'abnormalMortgageBatch.label', default: 'AbnormalMortgageBatch'), abnormalMortgageBatch.id])
                redirect action: "index", method: "GET"
            }
            '*' { respond abnormalMortgageBatch, [status: CREATED,flag:true] }
        }
    }

    //初始化工作流
    @Transactional
    def initWorkflow(AbnormalMortgageBatch abnormalMortgageBatch)
    {
        def workFlow = abnormalMortgageBatch?.workflow
        if (!workFlow)
        {
            flash.message = "请先选择工作流"
            redirect url: request.getHeader("referer")
            return
        }
        def workflowInstance = abnormalMortgageBatchService.initWorkflow(abnormalMortgageBatch,workFlow)
        if(workflowInstance){
            redirect action: 'pendingShow', params:[id:workflowInstance?.id]
            return
        }
        redirect url: request.getHeader("referer")
    }

    @Transactional
    def changeStatus(AbnormalMortgageBatch abnormalMortgageBatch)
    {
        abnormalMortgageBatch.status = "Failed"
        abnormalMortgageBatch.descriptionOfFailure = params['descriptionOfFailure']
        abnormalMortgageBatch.save flush: true

        redirect action: 'show', params: [id: abnormalMortgageBatch?.id]
    }

    @Transactional
    def disposalSave1()
    {
        def abnormalMortgageBatch = AbnormalMortgageBatch.findById(params['abnormalMortgageBatch'])
        def department = Department.findById(params['department'])
        abnormalMortgageBatch.disposalDepartment = department
        if (abnormalMortgageBatch.validate())
        {
            abnormalMortgageBatch.save flush: true
        }
        else
        {
            println abnormalMortgageBatch.errors
        }
        redirect url: request.getHeader('referer')
    }

    def disposalAsign(AbnormalMortgageBatch abnormalMortgageBatch)
    {
        params['targetUri'] = request.getHeader("referer")
        respond abnormalMortgageBatch, model: [params: params]
    }

    @Transactional
    def disposalAsignSave(AbnormalMortgageBatch abnormalMortgageBatch)
    {
        if (abnormalMortgageBatch.validate())
        {
            abnormalMortgageBatch.save flush: true
        }
        else
        {
            println abnormalMortgageBatch.errors
        }
        
        redirect url: params['targetUri']
    }
}
